package com.yhj.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import java.util.Arrays;

/**
 * @author yaohj
 * @date 2024年11月21日 16:30
 */
@Component
public class AnnotationAddingPostProcessor implements BeanPostProcessor {
    private static final Logger log = LoggerFactory.getLogger(AnnotationAddingPostProcessor.class);

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean; // 在初始化之前添加注解，但通常注解是在类加载时处理的，所以这里可能不会生效
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (isController(bean.getClass())) {
            // 检查是否已经有@Validated注解
            if (AnnotationUtils.findAnnotation(bean.getClass(), Validated.class) == null) {
               log.info(bean.getClass()+"");
            }
        }
        return bean;
    }

    private boolean isController(Class<?> clazz) {
        // 检查类是否有@Controller或@RestController注解
        return clazz.getAnnotation(org.springframework.web.bind.annotation.RestController.class)!=null ||
                clazz.getAnnotation(org.springframework.stereotype.Controller.class)!=null;
    }
}
